//
//  SuperCommentCell.m
//  LiveStar
//
//  Created by 漪珊 on 2017/5/12.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "SuperCommentCell.h"
#import "SuperCommentModel.h"
#import "CommentModel.h"

@interface SuperCommentCell()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *descLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIButton *replyBtn;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSIndexPath *indexPath;
@property (nonatomic, strong) SuperCommentModel *superModel;
@end
@implementation SuperCommentCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        self.headImageView = [[UIImageView alloc] init];
        self.headImageView.backgroundColor = [UIColor whiteColor];
        self.headImageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.contentView addSubview:self.headImageView];
        [self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(kGAP);
            make.width.height.mas_equalTo(kAvatar_Size);
        }];
        self.headImageView.clipsToBounds = YES;
        self.headImageView.layer.cornerRadius = kAvatar_Size/2;
        
        // nameLabel
        self.nameLabel = [UILabel new];
        [self.contentView addSubview:self.nameLabel];
        self.nameLabel.textColor = HESHEX_COLOR(@"333333");
        self.nameLabel.preferredMaxLayoutWidth = screenWidth - kGAP-kAvatar_Size - 2*kGAP-kGAP;
        self.nameLabel.numberOfLines = 0;
        //        self.nameLabel.displaysAsynchronously = YES;
        self.nameLabel.font = [UIFont systemFontOfSize:14.0];
        [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.headImageView.mas_right).offset(10);
            make.top.mas_equalTo(self.headImageView);
            make.right.mas_equalTo(-kGAP);
        }];
        
        //timeLabel
        self.timeLabel = [[UILabel alloc] init];
        [self.contentView addSubview:self.timeLabel];
        self.timeLabel.textColor = HESHEX_COLOR(@"999999");
        self.timeLabel.preferredMaxLayoutWidth = screenWidth - kGAP-kAvatar_Size - 2*kGAP-kGAP;
        self.timeLabel.numberOfLines = 0;
        //        self.nameLabel.displaysAsynchronously = YES;
        self.timeLabel.font = [UIFont systemFontOfSize:13.0];
        [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.headImageView.mas_right).offset(10);
            make.bottom.mas_equalTo(self.headImageView);
            make.right.mas_equalTo(-kGAP);
        }];
        
        //replyBtn
        self.replyBtn = [[UIButton alloc] init];
        self.replyBtn.titleLabel.font = UIFont(15);
        [self.replyBtn setTitleColor:HESHEX_COLOR(@"000000") forState:UIControlStateNormal];
        [self.replyBtn addTarget:self action:@selector(ReplyAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.replyBtn setTitle:@"回复" forState:UIControlStateNormal];
        [self.contentView addSubview:self.replyBtn];
        [self.replyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(10);
            make.right.mas_equalTo(-10);
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(60);
        }];
        
        // desc
        self.descLabel = [UILabel new];
        //        self.descLabel.displaysAsynchronously = YES;
        
        self.descLabel.backgroundColor = [UIColor whiteColor];
        UITapGestureRecognizer *tapText = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapText:)];
        [self.descLabel addGestureRecognizer:tapText];
        self.descLabel.textColor = HESHEX_COLOR(@"333333");
        [self.contentView addSubview:self.descLabel];
        self.descLabel.preferredMaxLayoutWidth =screenWidth - kGAP-kAvatar_Size ;
        self.descLabel.numberOfLines = 0;
        self.descLabel.font = [UIFont systemFontOfSize:14.0];
        [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.nameLabel);
            make.top.mas_equalTo(self.timeLabel.mas_bottom).offset(kGAP);
        }];
    
        self.tableView = [[UITableView alloc] init];
        self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        self.tableView.scrollEnabled = NO;
        [self.contentView addSubview:self.tableView];
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.descLabel);
            make.top.mas_equalTo(self.descLabel.mas_bottom).offset(kGAP);
            make.right.mas_equalTo(-kGAP);
        }];
        
        UIView *sepLine = [[UIView alloc] init];
        sepLine.backgroundColor = [UIColor cellLineColor];
        [self.contentView addSubview:sepLine];
        [sepLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.tableView.mas_bottom).offset(10);
            make.height.mas_equalTo(0.5);
            make.left.mas_equalTo(self.contentView);
            make.right.mas_equalTo(-kGAP);
        }];
        
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.hyb_lastViewInCell = sepLine;
        self.hyb_bottomOffsetToCell = 0.0;
    }
    
    return self;
}

//回复
- (void)ReplyAction:(UIButton *)sender {
    if (self.TapReplyBlock) {
        self.TapReplyBlock(sender);
    }
}

-(void)tapText:(UITapGestureRecognizer *)tap{
    if (self.TapTextBlock) {
        UILabel *descLabel = (UILabel *)tap.view;
        self.TapTextBlock(descLabel);
    }
}
- (void)configCellWithModel:(SuperCommentModel *)model indexPath:(NSIndexPath *)indexPath {
    self.indexPath = indexPath;
    
    self.nameLabel.text = model.u_nickname;
    self.timeLabel.text = model.c_createtime;
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:model.u_avatar] placeholderImage:kPlACE_ICON];
    
    //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //
    //        // Create attributed string.
    //        NSMutableAttributedString *messageText = [[NSMutableAttributedString alloc] initWithString:model.message];
    //        NSMutableAttributedString *userNameText = [[NSMutableAttributedString alloc] initWithString:model.userName];
    //
    //        messageText.yy_font = [UIFont systemFontOfSize:14.0];
    //        userNameText.yy_font = [UIFont systemFontOfSize:17.0];
    //
    //        messageText.yy_color = [UIColor blackColor];
    //        //        [text yy_setColor:[UIColor redColor] range:NSMakeRange(0, 4)];
    //        messageText.yy_lineSpacing = 2;
    ////        userNameText.yy_lineSpacing = 0;
    //
    //        // Create text container
    //        YYTextContainer *messageContainer = [YYTextContainer new];
    //        YYTextContainer *userNameContainer = [YYTextContainer new];
    //
    //        messageContainer.size = CGSizeMake([UIScreen mainScreen].bounds.size.width - kGAP-kAvatar_Size - 2*kGAP, CGFLOAT_MAX);
    //        userNameContainer.size = CGSizeMake([UIScreen mainScreen].bounds.size.width - kGAP-kAvatar_Size - 2*kGAP, CGFLOAT_MAX);
    //
    //        messageContainer.maximumNumberOfRows = 0;
    //        userNameContainer.maximumNumberOfRows = 0;
    //
    //        // Generate a text layout.
    //        YYTextLayout *messageLayout = [YYTextLayout layoutWithContainer:messageContainer text:messageText];
    //
    //        YYTextLayout *userNameLayout = [YYTextLayout layoutWithContainer:messageContainer text:userNameText];
    //
    //
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            self.descLabel.size = messageLayout.textBoundingSize;
    //            self.descLabel.textLayout = messageLayout;
    //
    //            self.nameLabel.size = userNameLayout.textBoundingSize;
    //            self.nameLabel.textLayout = userNameLayout;
    //        });
    //    });
    self.superModel = model;
    NSMutableParagraphStyle *muStyle = [[NSMutableParagraphStyle alloc]init];
    muStyle.lineSpacing = 3;//设置行间距离
    muStyle.alignment = NSTextAlignmentLeft;//对齐方式
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:model.c_content];
    [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14.0] range:NSMakeRange(0, attrString.length)];
//    [attrString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, attrString.length)];//下划线
    
    [attrString addAttribute:NSParagraphStyleAttributeName value:muStyle range:NSMakeRange(0, attrString.length)];
    self.descLabel.attributedText = attrString;
    
    self.descLabel.highlightedTextColor = HESHEX_COLOR(@"333333");//设置文本高亮显示颜色，与highlighted一起使用。
    self.descLabel.highlighted = YES; //高亮状态是否打开
    self.descLabel.enabled = YES;//设置文字内容是否可变
    self.descLabel.userInteractionEnabled = YES;//设置标签是否忽略或移除用户交互。默认为NO
    
    CGFloat tableViewHeight = 0;
    for (CommentModel *commentModel in model.commentArray) {
        CGFloat cellHeight = [CommentCell hyb_heightForTableView:self.tableView config:^(UITableViewCell *sourceCell) {
            CommentCell *cell = (CommentCell *)sourceCell;
            [cell configCellWithModel:commentModel];
        } cache:^NSDictionary *{
            return @{kHYBCacheUniqueKey : KString(commentModel.cid),
                     kHYBCacheStateKey : @"",
                     kHYBRecalculateForStateKey : @(YES)};
        }];
        tableViewHeight += cellHeight;
    }
    
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(tableViewHeight);
    }];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentCell"];
    if (!cell) {
        cell = [[CommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CommentCell"];
    }else{
        
    }
    
    CommentModel *model = [self.superModel.commentArray objectAtIndex:indexPath.row];
    [cell configCellWithModel:model];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.superModel.commentArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentModel *model = [self.superModel.commentArray objectAtIndex:indexPath.row];
    CGFloat cell_height = [CommentCell hyb_heightForTableView:self.tableView config:^(UITableViewCell *sourceCell) {
        CommentCell *cell = (CommentCell *)sourceCell;
        [cell configCellWithModel:model];
    } cache:^NSDictionary *{
        NSDictionary *cache = @{kHYBCacheUniqueKey : KString(model.cid),
                                kHYBCacheStateKey : @"",
                                kHYBRecalculateForStateKey : @(NO)};
        self.superModel.shouldUpdateCache = YES;
        return cache;
    }];
    return cell_height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.indexPath = indexPath;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CommentModel *commentModel = [self.superModel.commentArray objectAtIndex:indexPath.row];
    if ([commentModel.c_udid intValue] == [User_ID intValue]) {
        NSLog(@"这是自己的留言");
        return;
    }
    CGFloat cell_height = [CommentCell hyb_heightForTableView:self.tableView config:^(UITableViewCell *sourceCell) {
        CommentCell *cell = (CommentCell *)sourceCell;
        
        
        
        [cell configCellWithModel:commentModel];
    } cache:^NSDictionary *{
        NSDictionary *cache = @{kHYBCacheUniqueKey : KString(commentModel.cid),
                                kHYBCacheStateKey : @"",
                                kHYBRecalculateForStateKey : @(NO)};
        self.superModel.shouldUpdateCache = YES;
        return cache;
    }];
    
    
    if ([self.delegate respondsToSelector:@selector(passCellHeight:commentModel:commentCell:SuperCommentCell:)]) {
        CommentCell *commetCell =  (CommentCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        [self.delegate passCellHeight:cell_height commentModel:commentModel commentCell:commetCell SuperCommentCell:self];
        
    }
    
}
@end
